module AI
  attr_accessor :max_distance # when target gets this far away, start chasing
  attr_accessor :min_distance # when target is this close, stop chasing
  attr_accessor :target
  
  def initialize
    @direction ||= rand < 0.5 ? :left : :right
    @max_distance ||= 32
    @min_distance ||= 24
    @max_speed ||= 3
    super
  end
  
  def chase
    return unless following?
    @chasing = true if target_too_far?
    if @chasing
      return @chasing = false if @target.pos.distance_to(@pos) <= @min_distance
      move_towards @target.pos
      play_animation :move
    end
  end
  
  def direction_from_vector(vector)
    @direction = vector.x < 0 ? :left : :right
  end
  
  def follow(actor)
    @target = actor
  end
  
  def following?
    @target and @target.in_world?
  end

  def move_towards(point, options={})
    options[:speed] ||= @max_speed
    delta = point - @pos
    unless delta.length_squared == 0
      @vel = delta.normalize * options[:speed]
      direction_from_vector delta
      play_animation :move
    end
  end
  
  def random_action
    :idle
  end
  
  def random_point(options={})
    point = Point.new
    point.x = rand * (options[:range] || $window.width)
    point.y = rand * (options[:range] || $window.height)
    if options[:nearby]
      point.x = @pos.x + (rand < 0.5 ? point.x : -point.x)
      point.y = @pos.y + (rand < 0.5 ? point.y : -point.y)
    end
    point
  end
  
  def target_too_far?
    @target and @target.pos.distance_to(@pos) > @max_distance
  end
  
  def update
    chase
    super
  end
end
